/**
 * Copyright 2012 
 * 
 * Nicolas Desjardins  
 * https://github.com/mrKlar
 * 
 * Facilite solutions
 * http://www.facilitesolutions.com/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.hctforgreen.greenservice.ui.adapter;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hctforgreen.greenservice.CalculatorUtilsMainActivity;
import com.hctforgreen.greenservice.CaptureActivity;
import com.hctforgreen.greenservice.CompetingActivity;
import com.hctforgreen.greenservice.DebugActivity;
import com.hctforgreen.greenservice.DownloadManagerActivityV2;
import com.hctforgreen.greenservice.FeedbackActivity;
import com.hctforgreen.greenservice.MainActivityV2;
import com.hctforgreen.greenservice.MessageFirstActivityV2;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.SettingActivity;
import com.hctforgreen.greenservice.StartPwdActivity;
import com.hctforgreen.greenservice.TechnicalDataActivityV4;
import com.hctforgreen.greenservice.TerminalTrainActivity;
import com.hctforgreen.greenservice.TrainActivity;
import com.hctforgreen.greenservice.VideoTypesActivity;
import com.hctforgreen.greenservice.model.Item;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.MachineListEntity.MachineEntity;
import com.hctforgreen.greenservice.model.Page;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.MainMenuStoreUtil;
import com.umeng.analytics.MobclickAgent;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import ca.laplanete.mobile.pageddragdropgrid.PagedDragDropGrid;
import ca.laplanete.mobile.pageddragdropgrid.PagedDragDropGridAdapter;
import cn.dns.reader.network.Util;

public class MenuPagedDragDropGridAdapter implements PagedDragDropGridAdapter {

	private Activity context;
	private PagedDragDropGrid gridview;

	List<Page> pages = new ArrayList<>();
	private View msgView;
	private View assignView;
	
	/**
	 * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
	 */
	public int pingCount = 0;
	/**
	 * false为正式服务器，true为云服务器
	 */
	private boolean isCloudServer = false;
	private String[] funcsAll = {"1", "3", "4","17", "5", "6", "16", /* "20", */"7",
			"8", "9", /* "10" , 新闻*/"100","101" };// 所有权限

	// 100派工权限

	public MenuPagedDragDropGridAdapter(Activity context, PagedDragDropGrid gridview, int pingCount, boolean isClounServer) {
		super();
		this.context = context;
		this.gridview = gridview;
		initData();
        this.pingCount = pingCount;
        this.isCloudServer = isClounServer;
        /*if(!HctBackTestJsonController.isB_DEBUG()){
        	Log.i("DATA", "传到MenuPagedDragDropGridAdapter的--pingCount   " + this.pingCount);
     		Log.i("DATA", "传到MenuPagedDragDropGridAdapter的--isClounServer   " + this.isCloudServer);
		}*/
	}

	private void initData() {
		DecimalFormat format = new DecimalFormat("0");
		String localFuncs = MainMenuStoreUtil.get(context);
		/**
		 * 老版本未添加培训菜单,读取本地菜单可能会缺失
		 */
		if (!TextUtils.isEmpty(localFuncs) && !localFuncs.contains("!16!")) {// 加!便于正确判断菜单是否可点
			localFuncs += "!16!";
		}
		/**
		 * 加上竞品资料 if (!TextUtils.isEmpty(localFuncs) &&
		 * !localFuncs.contains("!20!")) {// 加!便于正确判断菜单是否可点 localFuncs +=
		 * "!20!"; }
		 */
		
		/**
		 * 20160908-- 390694  添加终端培训板块
		 * 老版本未添加终端培训菜单,读取本地菜单可能会缺失
		 */
		if (!TextUtils.isEmpty(localFuncs) && !localFuncs.contains("!17!")) {// 加!便于正确判断菜单是否可点
			localFuncs += "!17!";
		}
		
		String[] funcs = localFuncs.trim().length() > 0 ? localFuncs.split("!") : funcsAll;
		if (funcs != null && funcs.length > 0) {
			ArrayList<String> fucList = new ArrayList<>();
			for (String string : funcs) {
				if (string != null && string.trim().length() > 0) {
					fucList.add(string);
				}
			}

			if (!fucList.isEmpty()) {
				int size = 1;
				if (fucList.size() % 9 == 0) {
					size = fucList.size() / 9;
				} else {
					size = Integer.valueOf(format.format(Math.ceil(fucList.size() / 9)) + "") + 1;
				}
				for (int i = 0; i < size; i++) {
					pages.add(new Page());
				}
				for (int i = 0; i < fucList.size(); i++) {
					Page page = pages.get(Integer.valueOf(format.format(Math.floor(i / 9)) + ""));
					page.addItem(changeToItem(fucList.get(i)));
				}
				// if (loginResultEntity.assign.equals("1")) {// 拥有派工权限
				// Page page = pages.get(pages.size() - 1);
				// if (page.getItems().size() < 9) {
				// page.addItem(new Item(1000, "",
				// R.drawable.btn_main_dispatch));
				// } else {
				// Page newPage = new Page();
				// newPage.addItem(new Item(1000, "",
				// R.drawable.btn_main_dispatch));
				// pages.add(newPage);
				// }
				//
				// }
			}
		}
	}

	/**
	 * 将菜单转化为菜单项
	 * 
	 * @param func
	 * @return 菜单项
	 */
	private Item changeToItem(String func) {
		Item item = null;
		Integer fun = Integer.parseInt(func);
		switch (fun) {
		case 1:// 开机密码
			item = new Item(fun, "", R.drawable.btn_main_top_1);
			break;
		case 2:// 二维码下载
			item = new Item(fun, "", R.drawable.btn_main_top_2);
			break;
		case 3:// 调试维修
			item = new Item(fun, "", R.drawable.btn_main_top_3);
			break;
		case 4:// 通知
			item = new Item(fun, "", R.drawable.btn_main_center_1);
			break;
		case 5:// 技术资料
			item = new Item(fun, "", R.drawable.btn_main_center_2);
			break;
		case 6:// 信息反馈
			item = new Item(fun, "", R.drawable.btn_main_center_3);
			break;
		case 7:// 下载管理
			item = new Item(fun, "", R.drawable.btn_main_bottom_1);
			break;
		/*
		 * 390694
		 * 2016-10-07
		 * 2.4.0之前版本视频播放和设置权限值颠倒，
		 * 2.4.1修改此bug
		 * case 8:// 视频播放
			item = new Item(fun, "", R.drawable.btn_main_bottom_3);
			break;
		case 9:// 设置
			item = new Item(fun, "", R.drawable.btn_main_bottom_2);
			break;*/
		case 8:// 设置
			item = new Item(fun, "", R.drawable.btn_main_bottom_2);
			break;
		case 9:// 视频播放
			item = new Item(fun, "", R.drawable.btn_main_bottom_3);
			break;
		case 10:// 新闻
			item = new Item(fun, "", R.drawable.btn_main_news);
			break;
		case 16:// 培训
			item = new Item(fun, "", R.drawable.btn_main_train);
			break;
		// case 20:// 竞品资料
		// item = new Item(fun, "", R.drawable.btn_main_compet);
		// break;
		case 100:// 派工
			item = new Item(fun, "", R.drawable.btn_main_dispatch);
			break;
		case 101:// 格力小工具
			item = new Item(fun, "", R.drawable.btn_main_calculator_utils);
			break;
		 case 17:// 终端培训 ---20160908 390694 添加
             item = new Item(fun, "", R.drawable.btn_main_terminal_train);
             break;
		default:
//			item = new Item(fun, "", R.drawable.btn_main_bottom_2);
			break;
		}
		return item;
	}

	@Override
	public int pageCount() {
		return pages.size();
	}

	private List<Item> itemsInPage(int page) {
		if (pages.size() > page) {
			return pages.get(page).getItems();
		}
		return Collections.emptyList();
	}

	@Override
	public View view(int page, int index) {

		LoginResultEntity loginResultEntity = LoginResultStoreUtil.get(context);
		final String functions = loginResultEntity.functions;

		Item item = getItem(page, index);
		View view = context.getLayoutInflater().inflate(
				R.layout.layout_main_menu_item, null);
		ImageView btnMenu = (ImageView) view.findViewById(R.id.btn_main_menu);

		btnMenu.setImageResource(item.getDrawable());

		// LinearLayout layout = new LinearLayout(context);
		// layout.setOrientation(LinearLayout.VERTICAL);
		//
		// ImageView icon = new ImageView(context);
		// Item item = getItem(page, index);
		// icon.setImageResource(item.getDrawable());
		// // icon.setPadding(15, 15, 15, 15);
		//
		// layout.addView(icon);
		// layout.setTag(item);
		// // TextView label = new TextView(context);
		// // label.setTag(item);
		// // label.setText(item.getName());
		// // label.setTextColor(Color.BLACK);
		// // label.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
		// //
		// // label.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
		// // LayoutParams.WRAP_CONTENT));
		//
		// layout.setLayoutParams(new LinearLayout.LayoutParams(
		// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		// only set selector on every other page for demo purposes
		// if you do not wish to use the selector functionality, simply
		// disregard this code
		// if (page % 2 == 0) {
		// setViewBackground(view);
		view.setClickable(true);
		view.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View v) {
				return gridview.onLongClick(v);
			}
		});
		// }

		// layout.addView(label);

		if (item.getDrawable() == R.drawable.btn_main_center_1) {// 通知
			setMsgView(view);
		}

		if (!functions.contains(LoginResultEntity.FUNCTION_TAG + item.getId()
				+ LoginResultEntity.FUNCTION_TAG)) {
			btnMenu.setEnabled(false);
			btnMenu.setClickable(false);
		}

		if (item.getDrawable() == R.drawable.btn_main_dispatch) {// 派工
			assignView = view;
			assignView.setTag(item);
		}
		view.setTag(item);
		view.setOnClickListener(new MenuClickListener(item, functions));

		return view;
	}

	public void setAssignView() {
	}

	private void saveMenus() {
		if (pages == null || pages.isEmpty()) {
			return;
		}

		List<Item> items = new ArrayList<Item>();
		for (Page page : pages) {
			items.addAll(page.getItems());
		}
		StringBuilder sb = new StringBuilder();
		for (Item item : items) {
			sb.append("!").append(item.getId());
		}
		sb.append("!");
		MainMenuStoreUtil.save(context, sb.toString());
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void setViewBackground(LinearLayout layout) {
		if (android.os.Build.VERSION.SDK_INT >= 16) {
			layout.setBackground(context.getResources().getDrawable(
					R.drawable.list_selector_holo_light));
		}
	}

	private Item getItem(int page, int index) {
		List<Item> items = itemsInPage(page);
		return items.get(index);
	}

	@Override
	public int rowCount() {
		return 3;
	}

	@Override
	public int columnCount() {
		return 3;
	}

	@Override
	public int itemCountInPage(int page) {
		return itemsInPage(page).size();
	}

	public void printLayout() {
		int i = 0;
		for (Page page : pages) {
			Log.d("Page", Integer.toString(i++));

			for (Item item : page.getItems()) {
				Log.d("Item", Long.toString(item.getId()));
			}
		}
	}

	private Page getPage(int pageIndex) {
		return pages.get(pageIndex);
	}

	@Override
	public void swapItems(int pageIndex, int itemIndexA, int itemIndexB) {
		getPage(pageIndex).swapItems(itemIndexA, itemIndexB);
		saveMenus();
	}

	@Override
	public void moveItemToPreviousPage(int pageIndex, int itemIndex) {
		int leftPageIndex = pageIndex - 1;
		if (leftPageIndex >= 0) {
			Page startpage = getPage(pageIndex);
			Page landingPage = getPage(leftPageIndex);

			Item item = startpage.removeItem(itemIndex);
			landingPage.addItem(item);
			startpage.addItem(landingPage.getItems().get(
					landingPage.getItems().size() - 1));
			landingPage.removeItem(landingPage.getItems().size() - 1);
		}
		saveMenus();
	}

	@Override
	public void moveItemToNextPage(int pageIndex, int itemIndex) {
		int rightPageIndex = pageIndex + 1;
		if (rightPageIndex < pageCount()) {
			Page startpage = getPage(pageIndex);
			Page landingPage = getPage(rightPageIndex);

			Item item = startpage.removeItem(itemIndex);
			landingPage.addItem(item);

			startpage.addItem(landingPage.getItems().get(0));
			landingPage.removeItem(0);
		}
		saveMenus();
	}

	@Override
	public void deleteItem(int pageIndex, int itemIndex) {
		getPage(pageIndex).deleteItem(itemIndex);
	}

	@Override
	public int deleteDropZoneLocation() {
		return BOTTOM;
	}

	@Override
	public boolean showRemoveDropZone() {
		return true;
	}

	@Override
	public int getPageWidth(int page) {
		return 0;
	}

	@Override
	public Object getItemAt(int page, int index) {
		return getPage(page).getItems().get(index);
	}

	@Override
	public boolean disableZoomAnimationsOnChangePage() {
		return true;
	}

	public View getMsgView() {
		return msgView;
	}

	public void setMsgView(View msgView) {
		this.msgView = msgView;
	}

	class MenuClickListener implements OnClickListener {
		private Item item;

		private String functions;

		public MenuClickListener(Item item, String functions) {
			super();
			this.item = item;
			this.functions = functions;
		}

		@Override
		public void onClick(View v) {
			if (!functions.contains(LoginResultEntity.FUNCTION_TAG
					+ item.getId() + LoginResultEntity.FUNCTION_TAG)) {
				return;
			}
			switch (item.getDrawable()) {
			case R.drawable.btn_main_top_1:// 开机密码
				MobclickAgent.onEvent(context, "Account_start_pwd");
				Intent intent = new Intent(context, StartPwdActivity.class);
				// 选择是否需要定位并传参给下一个界面定位（默认是）
				intent.putExtra("loc", true);
				intent.putExtra("PING_COUNT", pingCount);
				intent.putExtra("WHICH_SERVER", isCloudServer);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_top_2:// 条码扫描
				MobclickAgent.onEvent(context, "Account_barcode_scan");
				intent = new Intent(context, CaptureActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				context.startActivityForResult(intent,
						MainActivityV2.ZXING_DATA);
				break;
			case R.drawable.btn_main_top_3:// 调试维修
				MobclickAgent.onEvent(context, "Account_debug_service");
				intent = new Intent(context, DebugActivity.class);
				// 传递值（可能会用于区别直接进入调试还是通过扫码进入）
				intent.putExtra("params", "");
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_center_1:// 最近通知
				MobclickAgent.onEvent(context, "Account_notification");
				intent = new Intent();
				intent.setClass(context, MessageFirstActivityV2.class);
				context.startActivityForResult(intent,
						MainActivityV2.REQUEST_UPDATE_MSG);
				break;
			case R.drawable.btn_main_center_2:// 技术资料
				MobclickAgent.onEvent(context, "Account_technical_data");
				intent = new Intent();
				intent.setClass(context, TechnicalDataActivityV4.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY,
						new MachineEntity());
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_center_3:// 信息反馈
				MobclickAgent.onEvent(context, "Account_feadback");
				intent = new Intent();
				intent.setClass(context, FeedbackActivity.class);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_compet:// 竞品资料
				intent = new Intent();
				intent.setClass(context, CompetingActivity.class);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_bottom_1:// 下载管理
				MobclickAgent.onEvent(context, "Account_download_management");
				intent = new Intent();
				intent.setClass(context, DownloadManagerActivityV2.class);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_bottom_2:// 设置
				MobclickAgent.onEvent(context, "Account_software_setting");
				intent = new Intent();
				intent.setClass(context, SettingActivity.class);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_bottom_3:// 视频
				intent = new Intent();
				intent.setClass(context, VideoTypesActivity.class);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_dispatch:// 格力派工
				startToDispatch();

				break;
			case R.drawable.btn_main_news:// 新闻

				break;
			case R.drawable.btn_main_train:// 培训
				intent = new Intent();
				intent.setClass(context, TrainActivity.class);
				context.startActivity(intent);
				break;
			case R.drawable.btn_main_calculator_utils:// 格力小工具
				MobclickAgent.onEvent(context, "Account_calculator_utils");
				intent = new Intent();
				intent.setClass(context, CalculatorUtilsMainActivity.class);
				context.startActivity(intent);
				break;
				
			case R.drawable.btn_main_terminal_train:// 终端培训 --2016.9.8 390694添加
                MobclickAgent.onEvent(context, "Account_terminal_tran");
                intent = new Intent();
                intent.setClass(context, TerminalTrainActivity.class);
                context.startActivity(intent);
                break;

			default:
				break;
			}

		}
	}

	public int getPageSize() {
		return pages.size();
	}
	/**
	 * 判断是否已经安装格力派工
	 */
	public void startToDispatch() {
		/**
		 * 判断是否已经安装格力派工
		 */
		String packageName = "com.gree.GreeAndroidApp.GreeAndroidApp";
		if (!isInstalled(context, packageName)) {
			new AlertDialog.Builder(context)
					.setTitle(
							context.getString(R.string.dialog_default_title_hint))
					.setMessage(
							context.getString(R.string.dispath_download_and_install))
					.setNeutralButton(
							context.getString(R.string.dispath_download_and_install),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Util.dowloadApk(context,
											Util.DISPATCH_APK_DOWNLOAD_URL,
											"greeDispatch");// 下载格力派工apk,并安装

								}
							})
					.setNegativeButton(context.getString(R.string.cancel_hint),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
			return;
		}

		try {
			String phone = LoginResultStoreUtil.get(context).phone;// 登录账号（手机号码或工号）
			Intent intent = new Intent("android.intent.action.GREE");// action
																		// 指向格力派工
			intent.putExtra("phone", phone);// 参数为 登录账号
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 判断应用是否已安装
	 * 
	 * @param context
	 * @param packageName
	 * @return
	 */

	private boolean isInstalled(Context context, String packageName) {
		final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
		List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
		if (pinfo != null) {
			for (int i = 0; i < pinfo.size(); i++) {
				String pn = pinfo.get(i).packageName;
				if (pn.equals(packageName))
					return true;
			}
		}
		return false;
	}

	public View getAssignView() {
		return assignView;
	}

	public void setAssignViewLogin(boolean enable) {
		if (enable && assignView != null) {
			ImageView btnMenu = (ImageView) assignView
					.findViewById(R.id.btn_main_menu);
			btnMenu.setEnabled(true);
			btnMenu.setClickable(true);
			Item item = (Item) assignView.getTag();
			btnMenu.setOnClickListener(new MenuClickListener(item,
					LoginResultStoreUtil.get(context).functions));
		}
	}
}
